package com.myworkspace.standard.common.base;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDao {
    private JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedJdbcTemplate;




    public <T> List<T> queryForModel(String sql, Class<T> clazz, Object... objs) throws Exception {
        List<Map<String, Object>> maps = this.jdbcTemplate.queryForList(sql, objs);
        return conv(maps,clazz);
    }

    public <T> List<T> conv(List<Map<String, Object>> maps, Class<T> clazz) throws InstantiationException, IllegalAccessException {
        Field[] declaredFields = clazz.getDeclaredFields();

        Map<String, Field> map = new HashMap<>();
        for (Field f : declaredFields) {
            f.setAccessible(true);
            if (f.isAnnotationPresent(TableId.class)) {
                // id
                TableId annotation = f.getAnnotation(TableId.class);
                map.put(annotation.value(), f);
            } else if (f.isAnnotationPresent(TableField.class)) {
                TableField annotation = f.getAnnotation(TableField.class);
                map.put(annotation.value(), f);
            }
        }
        List<T> list = new ArrayList<>();
        for (Map<String, Object> modelMap : maps) {
            T t = (T)clazz.newInstance();
            for (String key : map.keySet()) {
                Object value = modelMap.get(key);
                if (value != null) {
                    Field field = map.get(key);
                    field.set(t, value);
                }
            }
            list.add(t);
        }
        return list;
    }


    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public NamedParameterJdbcTemplate getNamedJdbcTemplate() {
        return namedJdbcTemplate;
    }

    public void setNamedJdbcTemplate(NamedParameterJdbcTemplate namedJdbcTemplate) {
        this.namedJdbcTemplate = namedJdbcTemplate;
    }
}
